package com.blb.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

/**
 * 验证码工具类
 */
public class CodeUtils {

    private static char[] arr = "QWERTYUIOPASDFGHJKLZXCVBNM0123456789".toCharArray();
    private static Random random = new Random();
    private static int width = 110;
    private static int height = 42;
    public static String randomString;


    public static BufferedImage newCode() throws IOException {
        char[] chars = new char[8];
        //创建图片对象
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //获取图片对象的画布
        Graphics gc = bufferedImage.getGraphics();

        //设置背景颜色
        gc.setColor(Color.pink);
        //填充矩形
        gc.fillRect(0,0, width, height);

        //随机生成4个字符
        Font font = new Font("微软雅黑", Font.BOLD, 30);
        gc.setFont(font);
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(arr.length);
            //随机字符
            char c = arr[index];
            chars[i] = c;

            //随机字体颜色
            Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
            gc.setColor(color);

            //写字
            gc.drawString(c+"", 20*(i+1), random.nextInt(31)+20);
        }
        randomString = String.valueOf(chars);

        //画线
        for (int i = 0; i < 20; i++) {
            Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
            gc.setColor(color);
            gc.drawLine(random.nextInt(width),random.nextInt(height),random.nextInt(width),random.nextInt(height));
        }
        ImageIO.write(bufferedImage, "jpg", new FileOutputStream("G:\\JAVA_project\\xrtqhText\\code.jpg"));

        return bufferedImage;
    }
}
